package com.ggh.jinjilive.ui.live;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.dyhdyh.support.countdowntimer.CountDownTimerSupport;
import com.dyhdyh.support.countdowntimer.OnCountDownTimerListener;
import com.ggh.jinjilive.BaseApplication;
import com.ggh.jinjilive.R;
import com.ggh.jinjilive.common.MerchantSession;
import com.ggh.jinjilive.databinding.ActivityAudienceLiveBinding;
import com.ggh.jinjilive.dialog.GiftListDialog;
import com.ggh.jinjilive.dialog.LiveOccludeDialog;
import com.ggh.jinjilive.dialog.LiveSendMessageDialog;
import com.ggh.jinjilive.listener.AddItemOnClickListener;
import com.ggh.jinjilive.listener.AddOnClickListener;
import com.ggh.jinjilive.listener.AddOnClickListener1;
import com.ggh.jinjilive.mobile.create.StartLiveMobile;
import com.ggh.jinjilive.mobile.home.live.LiveList;
import com.ggh.jinjilive.mobile.live.LiveMessageMobile;
import com.ggh.jinjilive.mobile.live.SellGoodsMobile;
import com.ggh.jinjilive.mobile.live.SendGiftMobole;
import com.ggh.jinjilive.mobile.live.im.CustomMessage;
import com.ggh.jinjilive.mobile.live.im.MessageEntity;
import com.ggh.jinjilive.mobile.live.im.MessageMobile;
import com.ggh.jinjilive.ui.BaseActivity;
import com.ggh.jinjilive.ui.live.adapter.TVLiveMessageAdapter;
import com.ggh.jinjilive.utils.ARouterUtils;
import com.ggh.jinjilive.utils.im.LiveMessageUtils;
import com.ggh.jinjilive.utils.im.TCConstants;
import com.ggh.jinjilive.utils.loginIMUtils;
import com.ggh.jinjilive.views.live.barrage.TCDanmuMgr;
import com.ggh.jinjilive.views.live.gift.bean.GiftDemoModel;
import com.ggh.jinjilive.views.live.gift.bean.UserDemoInfo;
import com.ggh.jinjilive.views.live.gift.interfacei.GiftModelI;
import com.ggh.jinjilive.views.live.pk.http.HttpRequests;
import com.ggh.jinjilive.views.live.redrain.RedPacketViewHelper;
import com.ggh.jinjilive.views.live.redrain.model.BoxInfo;
import com.ggh.jinjilive.views.live.redrain.model.BoxPrizeBean;
import com.ggh.jinjilive.views.live.v2.V2PULLLiveRoom;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.opensource.svgaplayer.SVGADrawable;
import com.opensource.svgaplayer.SVGAParser;
import com.opensource.svgaplayer.SVGAVideoEntity;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMGroupMemberInfoResult;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMValueCallback;
import com.tencent.live2.V2TXLiveDef;
import com.tencent.live2.V2TXLivePlayerObserver;
import com.umeng.commonsdk.debug.E;

import org.jetbrains.annotations.NotNull;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import pl.droidsonroids.gif.AnimationListener;
import pl.droidsonroids.gif.GifDrawable;


@Route(path = ARouterUtils.AudienceLiveActivity)
public class AudienceLiveActivity extends BaseActivity<ActivityAudienceLiveBinding> implements View.OnClickListener {
    //ViewModel
    private AudienceLiveViewModel audienceLiveViewModel;
    //直播拉流的视频播放器
    private V2PULLLiveRoom v2PULLLiveRoom;
    //进入直播间
    private StartLiveMobile startLiveMobile;
    //消息适配器
    private TVLiveMessageAdapter tvLiveMessageAdapter;
    /////////////////////////////////////////直播间信息开始///////////////////////////////////////////////////////
    //直播间人数
    private int liveStudioNumber = 0;




    /////////////////////////////////////////直播间信息结束///////////////////////////////////////////////////////

    /////////////////////////////////////////Dialog///////////////////////////////////////////////////////
    //发送消息
    private LiveSendMessageDialog liveSendMessageDialog;
    //退出提示
    private LiveOccludeDialog liveOccludeDialog;
    //礼物列表
    private GiftListDialog giftListDialog;
    /////////////////////////////////////////Dialog结束///////////////////////////////////////////////////////
    /////////////////////////////////////////红包雨开始///////////////////////////////////////////////////////
    //红包雨区分
    private int redRainDistinguish = 0;
    //gif提示
    private GifDrawable gifDrawablePrompt;
    //gif倒计时
    private GifDrawable gifDrawable;
    //红包雨
    private RedPacketViewHelper mRedPacketViewHelper;
    /////////////////////////////////////////红包雨结束///////////////////////////////////////////////////////
    /////////////////////////////////////////弹幕开始///////////////////////////////////////////////////////
    //弹幕弹框
    private TCDanmuMgr mDanmuMgr;
    /////////////////////////////////////////弹幕结束///////////////////////////////////////////////////////
    @Override
    public void initCreate() {
        super.initCreate();
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        BaseApplication.getInstance().getAppComponent().doInjectionMain(this);
        audienceLiveViewModel = new ViewModelProvider(this,viewModelFactory).get(AudienceLiveViewModel.class);

    }

    @Override
    public void initParam() {
        super.initParam();
        Intent intent = getIntent();
        startLiveMobile = (StartLiveMobile) intent.getSerializableExtra("StartLiveMobile");
        LiveList liveList = (LiveList) intent.getSerializableExtra("LiveList");
        if(null != audienceLiveViewModel){
            audienceLiveViewModel.liveList.set(liveList);
        }
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_audience_live;
    }

    @Override
    public void initView() {
        super.initView();
        //获取状态栏高度
        binding.llSpacing.setPadding(0, BarUtils.getStatusBarHeight(),0,0);
        //红包Gif
        Glide.with(binding.gifRed).asGif().load(R.mipmap.icon_gif_red).into(binding.gifRed);
        // 实例化 弹幕
        mDanmuMgr = new TCDanmuMgr(mContext);
        mDanmuMgr.setDanmakuView(binding.mDanmuView);
        //红包雨
        mRedPacketViewHelper = new RedPacketViewHelper(this);
        //发送消息
        liveSendMessageDialog = new LiveSendMessageDialog(this,R.style.DialogTheme);
        //退出提示
        liveOccludeDialog = new LiveOccludeDialog(mContext);
        //礼物
        giftListDialog = new GiftListDialog(mContext);
    }

    @Override
    public void initData() {
        super.initData();
        //消息适配器
        tvLiveMessageAdapter = new TVLiveMessageAdapter(mContext);
        tvLiveMessageAdapter.setAddItemOnClickListener(new AddItemOnClickListener() {
            @Override
            public void onSkipClicked(int position, Object mObject) {
                if(position == 0){
                    String messageEntity = (String) mObject;
                    if(null != liveSendMessageDialog && !liveSendMessageDialog.isShowing()) {
                        liveSendMessageDialog.show();
                        liveSendMessageDialog.etContent("@" + messageEntity);
                        liveSendMessageDialog.setAddOnClickListener(new AddOnClickListener() {
                            @Override
                            public void onSkipClicked(String sKip) {
                                sendMessage(sKip);
                                liveSendMessageDialog.dismiss();
                            }
                        });
                    }
                }
            }
        });
        binding.tvMessageList.setLayoutManager(new LinearLayoutManager(mContext));
        binding.tvMessageList.setAdapter(tvLiveMessageAdapter);
        //直播间信息
        audienceLiveViewModel.anchorView(userMobile.getUser_id());
        //获取倒计时
        audienceLiveViewModel.getServiceTime();
        //获取主播的带货列表
        audienceLiveViewModel.userTaskInfo();
        //观看直播
        v2PULLLiveRoom =  V2PULLLiveRoom.sharedInstance(mContext);
        //设置播放器渲染 View，该控件负责显示视频内容。
        v2PULLLiveRoom.setRenderView(binding.pusherTxCloudView);
        //设置播放器画面的旋转角度。
        v2PULLLiveRoom.setRenderRotation(V2TXLiveDef.V2TXLiveRotation.V2TXLiveRotation0);
        //设置画面的填充模式。
        v2PULLLiveRoom.setRenderFillMode(V2TXLiveDef.V2TXLiveFillMode.V2TXLiveFillModeFill);
        //开始播放音视频流。
        int result = v2PULLLiveRoom.startPlay(startLiveMobile.getRtmp_play_url());
        if (result != 0) {
            LogUtils.d("播放成员地址失败");
        }else {
            //加入群组
            loginIMUtils.joinGroup(audienceLiveViewModel.liveList.get().getRoom_id(),new V2TIMCallback() {
                @Override
                public void onSuccess() {
                    //更新直播间人数
                    getGroupMemberList();
                    //发送成功
                    loginIMUtils.setEnterTheStudio(userMobile, audienceLiveViewModel.liveList.get().getRoom_id(), new AddOnClickListener1() {
                        @Override
                        public void onSkipClicked(Object mObject) {
                            CustomMessage customMessage = (CustomMessage) mObject;
                            if(null != customMessage){
                                tvLiveMessageAdapter.setCustomMessage(customMessage);
                                binding.tvMessageList.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        binding.tvMessageList.scrollToPosition(tvLiveMessageAdapter.getCustomMessageList().size() - 1);
                                    }
                                });
                            }
                        }
                    });

                }

                @Override
                public void onError(int code, String desc) {
                    LogUtils.d(code + "进群失败" + desc);
                }
            });
        }
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //消息
        binding.imgLiveMessage.setOnClickListener(this);
        //连麦点击
        binding.llTvEvenMai.setOnClickListener(this);
        //关闭
        binding.imgLiveOcclude.setOnClickListener(this);
        //直播收缩
        binding.imgGift.setOnClickListener(this);
        //直播间信息
        audienceLiveViewModel.mLiveMessageMobile.observe(this, new Observer<LiveMessageMobile>() {
            @Override
            public void onChanged(LiveMessageMobile liveMessageMobile) {
                //主播头像
                Glide.with(binding.rivHeadLike).load(liveMessageMobile.getHead_portrait()).into(binding.rivHeadLike);
                //主播名称
                binding.tvNickname.setText(liveMessageMobile.getNickname());
                //主播ID
                binding.tvAnchorId.setText("ID:"+liveMessageMobile.getAnchor_id());
                //钻石
                binding.tvLiveDiamond.setText(liveMessageMobile.getMy_silver_wallet() +"");
                //守护
                binding.tvLiveGuardian.setText("守护：" + liveMessageMobile.getGuard_num() + "人");
            }
        });
        //获取倒计时
        audienceLiveViewModel.mInteger.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if(integer != 0){
                    CountDownTimerSupport countDownTimerSupport = new CountDownTimerSupport(1000 * integer, 1000);
                    //倒计时监听
                    countDownTimerSupport.setOnCountDownTimerListener(new OnCountDownTimerListener() {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            binding.tvCountDown.setText(millisUntilFinished / 1000 +"s");
                        }

                        @Override
                        public void onFinish() {
                            countDownTimerSupport.stop();
                            //获取倒计时
                            audienceLiveViewModel.getServiceTime();
                        }
                    });
                    countDownTimerSupport.start();
                }else {
                    LogUtils.d("获取倒计时错误");
                }
            }
        });

        //自定义消息回调
        loginIMUtils.addSimpleMsgListener(new AddItemOnClickListener() {
            @Override
            public void onSkipClicked(int position, Object mObject) {
                if(position == 0){//
                    String[] strings = (String[]) mObject;
                    if(strings.length > 0){
                        String adminUserName = strings[0];
                        String adminHead = strings[1];
                        String adminLevel = strings[2];
                        String adminGrand = strings[3];
                        String adminContent = strings[4];
                        String yellow = strings[5];
                        String level_img = strings[6];
                        CustomMessage customMessage = null;
                        if(yellow.equals("yellow")){
                            customMessage = new CustomMessage();
                            customMessage.cmd = "2";
                            MessageEntity messageEntity = new MessageEntity();
                            messageEntity.setRank(Integer.valueOf(adminLevel));
                            messageEntity.setNickname(adminUserName);
                            messageEntity.setLevel_img(level_img);
                            customMessage.msg = new Gson().toJson(messageEntity);
                            liveStudioNumber ++;
                            binding.tvLiveNumber.setText(liveStudioNumber +"");
                        }else if(yellow.equals("white")){
                            customMessage = new CustomMessage();
                            customMessage.cmd = "1";
                            MessageEntity messageEntity = new MessageEntity();
                            messageEntity.setRank(Integer.valueOf(adminLevel));
                            messageEntity.setNickname(adminUserName);
                            messageEntity.setLevel_img(level_img);
                            messageEntity.setMessage(adminContent);
                            customMessage.msg = new Gson().toJson(messageEntity);
                        }
                        //数据添加
                        LiveMessageUtils.getInstance().robotMessage(customMessage,tvLiveMessageAdapter,binding.tvMessageList);
                    }
                }else if(position == 1){
                    CustomMessage customMessage = (CustomMessage) mObject;
                    if(null != customMessage && null != tvLiveMessageAdapter){
                        MessageEntity messageEntity = null;
                        switch (customMessage.cmd){
                            case "1"://文字消息
                            case "2"://真人进房
                                messageEntity = new Gson().fromJson(customMessage.msg, MessageEntity.class);
                                break;
                            case "3"://真人退房
                                messageEntity = new Gson().fromJson(customMessage.msg, MessageEntity.class);
                                liveStudioNumber --;
                                binding.tvLiveNumber.setText(liveStudioNumber +"");
                                break;
                            case "5"://弹幕消息
                                messageEntity = new Gson().fromJson(customMessage.msg, MessageEntity.class);
                                if (mDanmuMgr != null) {
                                    mDanmuMgr.addDanmu(customMessage.userAvatar, customMessage.userName, messageEntity.getMessage());
                                }
                                break;
                            case "8"://直播礼物
                                messageEntity = new Gson().fromJson(customMessage.msg, MessageEntity.class);
                                MessageMobile messageMobile = new Gson().fromJson(messageEntity.getMessage(),MessageMobile.class);
                                //SVG动画
                                playSVGAnimation(messageMobile);
                                break;
                            case "10"://刷新钻石
                                messageEntity = new Gson().fromJson(customMessage.msg, MessageEntity.class);
                                LogUtils.d("钻石" + new Gson().toJson(messageEntity));
                                if(!TextUtils.isEmpty(messageEntity.getMessage())){
                                    //钻石
                                    binding.tvLiveDiamond.setText(messageEntity.getMessage());
                                }else {
                                    audienceLiveViewModel.anchorView(userMobile.getUser_id());
                                }
                                return;
                            case "18"://主播带货发送的商品

                                break;
                        }
                        if(null != messageEntity){
                            tvLiveMessageAdapter.setCustomMessage(customMessage);
                            binding.tvMessageList.post(new Runnable() {
                                @Override
                                public void run() {
                                    binding.tvMessageList.scrollToPosition(tvLiveMessageAdapter.getCustomMessageList().size() - 1);
                                }
                            });
                        }
                        //获取群成员列表
                        getGroupMemberList();
                    }
                }else if(position == 20){
                    SellGoodsMobile sellGoodsMobile = (SellGoodsMobile) mObject;
                    //直播带货
                    liveSellGoods(sellGoodsMobile);
                }else if(position == 21){
                    binding.llShopping.setVisibility(View.GONE);
                }
            }
        });

        //红包雨倒计时
        loginIMUtils.setGroupListener(new AddItemOnClickListener() {
            @Override
            public void onSkipClicked(int position, Object mObject) {
                if(position ==1001){//群解散
                    ToastUtils.make().show("主播下播了！");
                    v2PULLLiveRoom.stopPlay();
                    //关闭
                    finish();

                }else if(position == 101 || position == 6){
                    redRainDistinguish = position;
                    //红包雨倒计时
                    binding.llRedRain.setVisibility(View.VISIBLE);
                    //红包雨到时间
                    //GIF提示
                    if(null == gifDrawablePrompt){
                        gifDrawablePrompt = (GifDrawable) binding.gifCountdownPrompt.getDrawable();
                        gifDrawablePrompt.setLoopCount(0);
                    }
                    //GIF倒计时
                    if(null == gifDrawable){
                        gifDrawable = (GifDrawable) binding.gifCountdown.getDrawable();
                        gifDrawable.setLoopCount(0);
                        gifDrawable.addAnimationListener(new AnimationListener() {
                            @Override
                            public void onAnimationCompleted(int i) {
                                gifDrawablePrompt.stop();
                                gifDrawable.stop();
                                binding.llRedRain.setVisibility(View.GONE);
                                //红包雨下雨
                                mRedPacketViewHelper.endGiftRain();
                                getWindow().getDecorView().postDelayed(() -> {
                                    List<BoxInfo> boxInfos = new ArrayList<>();
                                    for (int redrain = 0; redrain < 100; redrain++) {
                                        BoxInfo boxInfo = new BoxInfo();
                                        boxInfo.setAwardId(redrain);
                                        boxInfo.setVoucher("ice " + redrain);
                                        boxInfos.add(boxInfo);
                                    }
                                    mRedPacketViewHelper.launchGiftRainRocket(0, boxInfos, new RedPacketViewHelper.GiftRainListener() {
                                        @Override
                                        public void startLaunch() {

                                        }

                                        @Override
                                        public void startRain() {

                                        }

                                        @Override
                                        public void openGift(BoxPrizeBean boxPrizeBean) {

                                        }

                                        @Override
                                        public void endRain() {

                                        }
                                    });
                                }, 0);
                            }
                        });
                    }
                    //GIF提示
                    if(null != gifDrawablePrompt && !gifDrawablePrompt.isRunning()){
                        gifDrawablePrompt.start();
                    }
                    if(null != gifDrawable && !gifDrawable.isRunning()){
                        gifDrawable.start();
                    }

                }
            }
        });
        //红包雨
        mRedPacketViewHelper.setAddOnClickListener(new AddOnClickListener() {
            @Override
            public void onSkipClicked(String sKip) {
                if(sKip.equals("开启")){
                    if(redRainDistinguish == TCConstants.IMCMD_HBRain){
                        //领取直播间红包雨
                        audienceLiveViewModel.getRedsrain();
                    }else if(redRainDistinguish == TCConstants.IMCMD_HBRain_ALL){
                        //领取平台红包雨
                        audienceLiveViewModel.getRedsrains();
                    }
                }
            }
        });
        //用户端正在带货的商品
        audienceLiveViewModel.mSellGoodsMobile.observe(this, new Observer<SellGoodsMobile>() {
            @Override
            public void onChanged(SellGoodsMobile sellGoodsMobile) {
                //直播带货
                liveSellGoods(sellGoodsMobile);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.img_live_message://发送消息
                if(null != liveSendMessageDialog && !liveSendMessageDialog.isShowing()) {
                    liveSendMessageDialog.show();
                    liveSendMessageDialog.setAddOnClickListener(new AddOnClickListener() {
                        @Override
                        public void onSkipClicked(String sKip) {
                            sendMessage(sKip);
                            liveSendMessageDialog.dismiss();
                        }
                    });
                }
                break;
            case R.id.img_gift://礼物弹框
                if(null != giftListDialog && !giftListDialog.isShowing()){
                    giftListDialog.show();
                    giftListDialog.roomData(audienceLiveViewModel.liveList.get().getUser_id(),
                            audienceLiveViewModel.liveList.get().getLive_id());
                    giftListDialog.setAddItemOnClickListener(new AddItemOnClickListener() {
                        @Override
                        public void onSkipClicked(int position, Object mObject) {
                            SendGiftMobole sendGiftMobole = (SendGiftMobole) mObject;
                            if(null != sendGiftMobole){
                                sendGiftMobole.setGiftNum(position);
                                //发送礼物消息
                                loginIMUtils.sendGift(sendGiftMobole, audienceLiveViewModel.liveList.get().getRoom_id(), new AddOnClickListener1() {
                                    @Override
                                    public void onSkipClicked(Object mObject) {

                                    }
                                });
                                //添加消息
                                CustomMessage customMessage = new CustomMessage();
                                customMessage.cmd = "8";
                                //用户
                                MessageEntity messageEntity = new MessageEntity();
                                messageEntity.setRank(userMobile.getLevel());
                                messageEntity.setNickname(userMobile.getNickname());
                                messageEntity.setLevel_img(userMobile.getLevel_img());
                                messageEntity.setAvatar(userMobile.getHead_portrait());
                                //礼物消息
                                MessageMobile messageMobile = new MessageMobile();
                                messageMobile.setNumber(position);
                                messageMobile.setName(sendGiftMobole.getName());
                                messageEntity.setMessage(new Gson().toJson(messageMobile));
                                customMessage.msg = new Gson().toJson(messageEntity);
                                messageMobile.setNickname(messageEntity.getNickname());
                                messageMobile.setHead_portrait(messageEntity.getAvatar());
                                messageMobile.setStatic_img_url(sendGiftMobole.getStatic_img_url());
                                messageMobile.setDynamic_img_url(sendGiftMobole.getDynamic_img_url());
                                messageMobile.setIs_show(sendGiftMobole.getIs_show());
                                //SVG动画
                                playSVGAnimation(messageMobile);
                                if(null != customMessage){
                                    tvLiveMessageAdapter.setCustomMessage(customMessage);
                                    binding.tvMessageList.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            binding.tvMessageList.scrollToPosition(tvLiveMessageAdapter.getCustomMessageList().size() - 1);
                                        }
                                    });
                                }
                            }
                        }
                    });
                }
                break;
            case R.id.img_live_occlude://关闭
                //关闭退款
                shutDownPage();
                break;
        }
    }

    /**
     * 直播带货
     * @param sellGoodsMobile
     */
    public void liveSellGoods(SellGoodsMobile sellGoodsMobile){
        if(null != sellGoodsMobile){
            binding.llShopping.setVisibility(View.VISIBLE);
            try {
                //商品图片
                Glide.with(mContext).load(sellGoodsMobile.getImg()).into(binding.imgSellGoods);
            }catch (Exception e){
                e.getMessage();
            }
            //商品名称
            binding.tvName.setText(sellGoodsMobile.getName());
            //价格
            binding.tvPrice.setText("￥"+sellGoodsMobile.getPrice());
        }
    }


    /**
     * 发送消息
     * @param sKip
     */
    public void sendMessage(String sKip){
        //弹幕
        if(liveSendMessageDialog.play){
            if (mDanmuMgr != null) {
                mDanmuMgr.addDanmu(userMobile.getHead_portrait(), userMobile.getNickname(), sKip);
            }
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setMessage(sKip);
            messageEntity.setNickname(MerchantSession.getInstance().getUser().getNickname());
            messageEntity.setRank(MerchantSession.getInstance().getUser().getLevel());
            messageEntity.setLevel_img(MerchantSession.getInstance().getUser().getLevel_img());
            messageEntity.setType("white");
            messageEntity.setIs_guard("");
            //发生自定义消息
            loginIMUtils.sendGroupCustomMessage("5", new Gson().toJson(messageEntity), audienceLiveViewModel.liveList.get().getRoom_id(), new V2TIMValueCallback<V2TIMMessage>() {
                @Override
                public void onSuccess(V2TIMMessage v2TIMMessage) {
                    LogUtils.d("成功");
                    //添加消息
                    CustomMessage customMessage = new CustomMessage();
                    customMessage.cmd = "5";
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setRank(Integer.valueOf(userMobile.getLevel()));
                    messageEntity.setNickname(userMobile.getNickname());
                    messageEntity.setLevel_img(userMobile.getLevel_img());
                    messageEntity.setMessage(sKip);
                    customMessage.msg = new Gson().toJson(messageEntity);
                    if(null != customMessage){
                        tvLiveMessageAdapter.setCustomMessage(customMessage);
                        binding.tvMessageList.post(new Runnable() {
                            @Override
                            public void run() {
                                binding.tvMessageList.scrollToPosition(tvLiveMessageAdapter.getCustomMessageList().size() - 1);
                            }
                        });
                    }
                }

                @Override
                public void onError(int code, String desc) {
                    LogUtils.d(code + "发送失败" + desc);
                }
            });
        }else {
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setMessage(sKip);
            messageEntity.setNickname(MerchantSession.getInstance().getUser().getNickname());
            messageEntity.setRank(MerchantSession.getInstance().getUser().getLevel());
            messageEntity.setLevel_img(MerchantSession.getInstance().getUser().getLevel_img());
            messageEntity.setType("white");
            messageEntity.setIs_guard("");
            //发生自定义消息
            loginIMUtils.sendGroupCustomMessage("1", new Gson().toJson(messageEntity), audienceLiveViewModel.liveList.get().getRoom_id(), new V2TIMValueCallback<V2TIMMessage>() {
                @Override
                public void onSuccess(V2TIMMessage v2TIMMessage) {
                    LogUtils.d("成功");
                    //添加消息
                    CustomMessage customMessage = new CustomMessage();
                    customMessage.cmd = "1";
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setRank(Integer.valueOf(userMobile.getLevel()));
                    messageEntity.setNickname(userMobile.getNickname());
                    messageEntity.setLevel_img(userMobile.getLevel_img());
                    messageEntity.setMessage(sKip);
                    customMessage.msg = new Gson().toJson(messageEntity);
                    if(null != customMessage){
                        tvLiveMessageAdapter.setCustomMessage(customMessage);
                        binding.tvMessageList.post(new Runnable() {
                            @Override
                            public void run() {
                                binding.tvMessageList.scrollToPosition(tvLiveMessageAdapter.getCustomMessageList().size() - 1);
                            }
                        });
                    }
                }

                @Override
                public void onError(int code, String desc) {
                    LogUtils.d(code + "发送失败" + desc);
                }
            });
        }
    }

    /**
     * SVG动画
     * @param messageMobile
     */
    public void playSVGAnimation(MessageMobile messageMobile){
        LogUtils.d("SVG动画" + new Gson().toJson(messageMobile));
        UserDemoInfo info = new UserDemoInfo();
        info.setName(messageMobile.getNickname());
        info.setUserId(messageMobile.getUser_id() + "");
        info.setGiftName("送一个"+ messageMobile.getName());
        info.setPortraitUri(messageMobile.getHead_portrait());
        GiftModelI model = new GiftDemoModel(messageMobile.getStatic_img_url());
        binding.liveGift.showNewGift(mContext, info, model);
        if(messageMobile.getIs_show() == 1){
            try { // new URL needs try catch.
                SVGAParser parser = SVGAParser.Companion.shareParser();
                parser.decodeFromURL(new URL(messageMobile.getDynamic_img_url()), new SVGAParser.ParseCompletion() {
                    @Override
                    public void onComplete(@NotNull SVGAVideoEntity videoItem) {
                        SVGADrawable drawable = new SVGADrawable(videoItem);
                        binding.liveSvg.setImageDrawable(drawable);
                        binding.liveSvg.startAnimation();
                    }
                    @Override
                    public void onError() {

                    }
                });
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
    }



    //获取群成员列表
    private void getGroupMemberList(){
        // 获取群成员列表
        loginIMUtils.getGroupMemberList(audienceLiveViewModel.liveList.get().getLive_id() +"", new V2TIMValueCallback<V2TIMGroupMemberInfoResult>() {
            @Override
            public void onSuccess(V2TIMGroupMemberInfoResult v2TIMGroupMemberInfoResult) {
                LogUtils.d("获取群成员列表" + v2TIMGroupMemberInfoResult.getMemberInfoList().size());
                liveStudioNumber = liveStudioNumber + v2TIMGroupMemberInfoResult.getMemberInfoList().size();
                binding.tvLiveNumber.setText(liveStudioNumber +"");
            }

            @Override
            public void onError(int code, String desc) {
                LogUtils.d(code + "获取群成员列表" + desc);
            }
        });
    }




    @Override
    protected void onDestroy() {
        //退出群组
        loginIMUtils.quitGroup(audienceLiveViewModel.liveList.get().getRoom_id(),null);
        super.onDestroy();
        if (v2PULLLiveRoom != null) {
            v2PULLLiveRoom.setObserver();
            v2PULLLiveRoom.stopPlay();
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 按下键盘上返回按钮
        if(keyCode == KeyEvent.KEYCODE_BACK){
            shutDownPage();
            return true;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }



    /**
     * 关闭页面
     */
    public void shutDownPage(){
        if(null != liveOccludeDialog && !liveOccludeDialog.isShowing()){
            liveOccludeDialog.show();
            liveOccludeDialog.setAddItemOnClickListener(new AddItemOnClickListener() {
                @Override
                public void onSkipClicked(int position, Object mObject) {
                    loginIMUtils.setExitStudio(userMobile, audienceLiveViewModel.liveList.get().getRoom_id(), new AddOnClickListener1() {
                        @Override
                        public void onSkipClicked(Object mObject) {
                            if(mObject.equals("发送成功")){
                                liveOccludeDialog.dismiss();
                                v2PULLLiveRoom.stopPlay();
                                //关闭
                                finish();
                            }
                        }
                    });
                }
            });
        }
    }
}
